import { uuid } from '@/utils'
import type { TableColumn } from '@/types'
import { queryTools, loadIndicatorsByGatewayPage } from '@/api/modules/gateway'

export interface IndicatorData {
  /** 测点编码 */
  code: string
  /** 测点名称 */
  name: string
  /** 计量单位 */
  unit: string
  /** 对应计量器具编号 */
  measuringToolNumber: string

  [key: string]: any
}

export function useTableData() {
  const columns: TableColumn<IndicatorData>[] = [
    {
      key: uuid(),
      label: '测点编码',
      prop: 'code',
      render({ row }) {
        return h('code', row.code)
      },
    },
    { key: uuid(), label: '测点名称', prop: 'name' },
    { key: uuid(), label: '计量单位', prop: 'unit' },
    { key: uuid(), label: '对应计量器具编号', prop: 'measuringToolNumber' },
  ]
  const [loading, setLoading] = useState(false)
  const tableData = shallowRef<IndicatorData[]>([])
  const pagination = reactive({
    pageNumber: 1,
    pageSize: 10,
    total: 0,
  })

  const toolsList = shallowRef<any[]>([])

  async function getLists(params: any) {
    setLoading(true)
    try {
      const { data } = await loadIndicatorsByGatewayPage(
        params.gatewayId,
        params.pageNumber,
        params.pageSize,
        params.measuringToolNumber,
      )
      tableData.value = (data.records ?? []).map((v: any) => ({
        id: v.id,
        code: v.measuringPointNumber,
        name: v.indicatorName,
        unit: v.unit,
        measuringToolNumber: v.toolCode,
      }))
      pagination.total = data.total ?? 0
    }
    finally {
      setLoading(false)
    }
  }

  async function getToolsList(gatewayId: number) {
    try {
      const { data } = await queryTools(gatewayId)
      toolsList.value = (data ?? []).map((v: any) => ({
        name: v.name,
        value: v.id,
        code: v.code,
      }))
    }
    catch (e) {}
  }

  return {
    tableData,
    pagination,
    columns,
    toolsList,
    loading,
    getLists,
    getToolsList,
  }
}
